
//     描述: 随机产生三个数并对这些数进行加减算法，运算结果在 0 < x < 27;
// 注意事项: 在使用rand()函数之前，先使用srand(unsigned int seed)初始化随机数发生器;
// 使用方法：见最后参考函数

#include <stdio.h>
#include <time.h>

static const int nleft = 1;
static const int nright = 10;

// a + b + c
int doubleadd()
{
	int a = (rand()%(nright - nleft)) + nleft;
	int b = (rand()%(nright - nleft)) + nleft;
	int c = (rand()%(nright - nleft)) + nleft;
	
	if (a + b == 18)
	{
		if (c == 9)
			c -= 1;
	}

	int d = a + b + c;
	printf("%d + %d + %d = %d\n", a, b, c, d);

	return d;
}

// a + b - c
int addandsub()
{
	int a = (rand()%(nright - nleft)) + nleft;
	int b = (rand()%(nright - nleft)) + nleft;
	int c = 0;

	int tmp = a + b;

	if (tmp > 9)	// a + b 大于9, c 只要在1至10内即可
		c = (rand()%(nright - nleft)) + nleft;
	else			// a + b 小于等于9, c 只能在1至a + b 之内
		c = (rand()%(tmp - nleft)) + nleft;

	int d = a + b - c;
	printf("%d + %d - %d = %d\n", a, b, c, d);

	return d;
}

// a - b - c
int doublesub()
{
	int a = (rand()%(nright - nleft)) + nleft;
	int b = (rand()%(nright - nleft)) + nleft;
	int c = 0;
	int tmp = a - b;
	
	if (tmp == 0)
	{
		int c = (rand()%(nright - nleft)) + nleft;
		int d = a - b + c;
		printf("%d - %d + %d = %d\n", a, b, c, d);

		return d;
	}
	else if (tmp < 0)	// 因为a - b 少于0, 所以C必须要大于a - b 的绝对值, 取值范围 (|x| + 1, nright)
	{
		int absolute = 0 - tmp + 1;
		c = (rand()%(nright - absolute)) + absolute;
		int d = a - b + c;
		printf("%d - %d + %d = %d\n", a, b, c, d);

		return d;
	}
	else
	{
		if (tmp == 1)		// a - b = 1, 1 - nleft = 0, 分母不能为0, 所以调整a或者b的值
		{
			if (a == 9)
			{
				b -= 1;
				tmp += 1;
			}
			else
			{
				a += 1;
				tmp += 1;
			}
		}

		c = (rand()%(tmp - nleft)) + nleft;
		int d = a - b - c;
		printf("%d - %d - %d = %d\n", a, b, c, d);

		return d;
	}
}

//a - b + c
int subandadd()
{
	int a = (rand()%(nright - nleft)) + nleft;
	int b = (rand()%(nright - nleft)) + nleft;
	int c = 0;
	int tmp = a - b;

	if (tmp == 0)
	{
		c = (rand()%(nright - nleft)) + nleft;
	}
	else if (tmp < 0)	// 因为a - b 少于0, 所以C必须要大于a - b 的绝对值, 取值范围 (|x| + 1, nright)
	{
		int absolute = 0 - tmp + 1;
		c = (rand()%(nright - absolute)) + absolute;
	}
	else	// a - b 已经大于0，c的取值在1至9就可以
	{
		c = (rand()%(nright - nleft)) + nleft;
	}

	int d = a -b + c;
	printf("%d - %d + %d = %d\n", a, b, c, d);

	return d;
}

typedef int (*mathhandler)();

mathhandler handlerfunc[] = {
	doubleadd,		// a + b + c
	addandsub,		// a + b - c
	doublesub,		// a - b - c
	subandadd		// a - b + c
};

// test 
int main(int argc, char **argv)
{
	srand((unsigned int)time(NULL));

	int number[5] = {0, 0, 0, 0, 0};
	int i = 0;
	for (i = 0; i < 1000; i++)
	{
		int tmp = rand();
		int a = tmp%4;

		number[a] ++;

		if (handlerfunc[a]() >= 27)
			number[4]++;
	}

	printf("number[1] = %d\n", number[0]);
	printf("number[2] = %d\n", number[1]);
	printf("number[3] = %d\n", number[2]);
	printf("number[4] = %d\n", number[3]);
	printf("number[5] = %d\n", number[4]);

	return 0;
}

